package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gzhc365.arch.component.excel.ExcelHelper;
import com.gzhc365.arch.component.excel.param.DownloadParam;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: hewenjuan
 * @date: Created in 2022/3/4 10:48
 * @version:
 * @modified By:
 */
public class Test {
    @Resource
    private ExcelHelper excelHelper;

    public void downLoad() throws Exception{
        //封装导入参数
        DownloadParam<AlarmInfo> downloadParam = new DownloadParam<>();
        String fileName = "告警记录.xlsx";
        //构建待写入的数据集 以实际业务为准 此处示例只是for循环去添加
//        List<AlarmInfo> dataList = new ArrayList<>();
        String path = Test.class.getClassLoader().getResource("excel.json").getPath();
        String s = readJsonFile(path);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String r = jsonObject.getString("rows");
        List<AlarmInfo> dataList = JSON.parseArray(r, AlarmInfo.class);
        downloadParam.setDomainList(dataList);
        downloadParam.setFileName(fileName);
        downloadParam.setTemplate(AlarmInfo.class);
        //调用导入接口
        excelHelper.download(downloadParam);
    }



    /**
     * 读取json文件，返回json串
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);

            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
